package cn.cttic.app.api.controller;

import cn.cttic.base.api.domain.bo.BaseDeviceBo;
import cn.cttic.base.api.domain.bo.BaseProductBo;
import cn.cttic.base.api.domain.vo.BaseCompanyVo;
import cn.cttic.base.api.domain.vo.BaseDeviceVo;
import cn.cttic.base.api.domain.vo.BaseProductVo;
import cn.cttic.base.api.domain.vo.BaseUserVo;
import cn.cttic.common.core.service.DictService;
import cn.cttic.order.api.domain.BaseSaleOrder;
import cn.cttic.order.api.domain.bo.BaseSaleOrderBo;
import cn.cttic.order.api.domain.vo.BaseSaleOrderVo;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import cn.cttic.app.api.domain.bo.*;
import cn.cttic.app.api.domain.vo.*;
import cn.cttic.app.api.enums.SaleOrderStatus;
import cn.cttic.app.mapper.BaseSaleOrderMapper;
import cn.cttic.app.service.*;
import cn.cttic.common.core.constant.CacheConstants;
import cn.cttic.common.core.domain.R;
import cn.cttic.common.mybatis.core.page.TableDataInfo;
import cn.cttic.common.redis.utils.RedisUtils;
import cn.cttic.common.satoken.model.AppLoginUser;
import cn.cttic.common.satoken.utils.AppLoginHelper;
import cn.cttic.resource.api.RemoteFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 移动端 - 销售接口
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mini/sale")
@Slf4j
public class AppSaleController {

    private final IBaseCompanyService baseCompanyService;

    private final IBaseProductService baseProductService;

    private final IBaseSaleOrderService baseSaleOrderService;

    private final IBaseDeviceService baseDeviceService;

    private final BaseSaleOrderMapper baseSaleOrderMapper;

    private final IAppInstallService appInstallService;
    private final IAppSaleService appSaleService;

    @DubboReference
    private RemoteFileService remoteFileService;

    // 短信接口
    private final IAppSmsService appSmsService;

    /**
     * 获取销售订单统计数据
     */
    @PostMapping("/getSaleOrderStatistic")
    public R<?> getSaleOrderStatistic() {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {

            List<BaseSaleOrder> saleOrderList = baseSaleOrderMapper.selectList(
                new LambdaUpdateWrapper<BaseSaleOrder>()
                    .eq(BaseSaleOrder::getSalesManId, loginUser.getUserId())
            );

            Map<Integer, List<BaseSaleOrder>> s = saleOrderList.stream().collect(Collectors.groupingBy(BaseSaleOrder::getStatus));
            Map<Integer, Integer> statisMap = new HashMap<>();

            for (SaleOrderStatus sos : SaleOrderStatus.values()) {
                if (s.containsKey(sos.getValue())) {
                    statisMap.put(sos.getValue(), s.get(sos.getValue()).size());
                } else {
                    statisMap.put(sos.getValue(), 0);
                }
            }

            return R.ok(statisMap);

        } catch (Exception e) {
            return R.fail("获取销售订单统计数据");
        }
    }

    /**
     * 测试： 添加设备型号
     */
    @PostMapping("/testAddDevice")
    public R<?> testAddDevice(@RequestBody @Validated BaseDeviceBo bo) {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {

            Boolean result = baseDeviceService.insertByBo(bo);
            return R.ok(result);

        } catch (Exception e) {
            return R.fail("添加设备型号失败");
        }
    }

    /**
     * 测试： 添加产品套餐
     */
    @PostMapping("/testAddProduct")
    public R<?> testAddProduct(@RequestBody @Validated BaseProductBo bo) {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {

            Boolean result = baseProductService.insertByBo(bo);
            return R.ok(result);

        } catch (Exception e) {
            return R.fail("添加产品套餐失败");
        }
    }


    /**
     * 获取产品套餐列表
     */
    @GetMapping("/getProductList")
    public R<?> getProductList() {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {

            List<BaseProductVo> productVoList = baseProductService.queryList(new BaseProductBo());
            return R.ok(productVoList);

        } catch (Exception e) {
            return R.fail("获取产品套餐列表失败");
        }
    }

    /**
     * 获取产品套餐分页列表
     */
    @GetMapping("/getProductPageList")
    public TableDataInfo getProductPageList(@Validated ProductQueryBo bo) {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {
            TableDataInfo<BaseProductVo> productVoTableDataInfo = baseProductService.queryPageList(new BaseProductBo(), bo);
            List<BaseProductVo> productVos = productVoTableDataInfo.getRows();
            productVos.forEach(vo -> {
                String productPosterUrl = remoteFileService.selectUrlByIds(vo.getProductPoster());
                vo.setProductPosterUrl(productPosterUrl);
                String productThumbnailUrl = remoteFileService.selectUrlByIds(vo.getProductThumbnail());
                vo.setProductThumbnailUrl(productThumbnailUrl);

                BaseDeviceVo baseDeviceVo = baseDeviceService.queryById(vo.getDeviceId());
                String devicePosterUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDevicePoster());
                baseDeviceVo.setDevicePosterUrl(devicePosterUrl);
                String deviceThumbnailUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDeviceThumbnail());
                baseDeviceVo.setDeviceThumbnailUrl(deviceThumbnailUrl);
                vo.setDeviceInfo(baseDeviceVo);
            });
            productVoTableDataInfo.setRows(productVos);
            return productVoTableDataInfo;

        } catch (Exception e) {
            return new TableDataInfo();
        }
    }


    /**
     * 获取产品套餐分页列表
     */
    @GetMapping("/getProductDetail")
    public R<?> getProductDetail(@RequestParam(value = "id", required = true) String id) {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {
            BaseProductVo baseProductVo = baseProductService.queryById(id);
            String productPosterUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductPoster());
            baseProductVo.setProductPosterUrl(productPosterUrl);
            String productThumbnailUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductThumbnail());
            baseProductVo.setProductThumbnailUrl(productThumbnailUrl);

            BaseDeviceVo baseDeviceVo = baseDeviceService.queryById(baseProductVo.getDeviceId());
            String devicePosterUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDevicePoster());
            baseDeviceVo.setDevicePosterUrl(devicePosterUrl);
            String deviceThumbnailUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDeviceThumbnail());
            baseDeviceVo.setDeviceThumbnailUrl(deviceThumbnailUrl);
            baseProductVo.setDeviceInfo(baseDeviceVo);

            return R.ok(baseProductVo);

        } catch (Exception e) {
            return R.fail("查询产品套餐详情失败");
        }
    }


    /**
     * 获取销售订单列表
     */
    @GetMapping("/getSaleOrderList")
    public R<?> getSaleOrderList() {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {

            List<BaseSaleOrderVo> productVoList = baseSaleOrderService.queryList(new BaseSaleOrderBo());
            return R.ok(productVoList);

        } catch (Exception e) {
            return R.fail("获取销售订单列表失败");
        }
    }

    private final IBaseUserService baseUserService;
    private final DictService dictService;

    /**
     * 获取销售订单分页列表
     */
    @GetMapping("/getSaleOrderPageList")
    public TableDataInfo getSaleOrderPageList(@Validated SaleOrderQueryBo bo) {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();
        BaseUserVo baseUserVo = baseUserService.queryById(loginUser.getId());
        BaseCompanyVo baseCompanyVo = baseCompanyService.queryById(baseUserVo.getCompanyId());
        String channel = dictService.getDictLabel("dict_channel_type", baseCompanyVo.getChannelType());

        try {
            TableDataInfo<BaseSaleOrderVo> productVoList = baseSaleOrderService.searchPageList(bo, loginUser.getUserId());
            List<BaseSaleOrderVo> productVos = productVoList.getRows();
            productVos.forEach(vo -> {
                BaseProductVo baseProductVo = baseProductService.queryById(vo.getProductId());
                String productPosterUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductPoster());
                baseProductVo.setProductPosterUrl(productPosterUrl);
                String productThumbnailUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductThumbnail());
                baseProductVo.setProductThumbnailUrl(productThumbnailUrl);
                vo.setProductThumbnailUrl(productThumbnailUrl);
                vo.setProductInfo(baseProductVo);
            });
            productVoList.setRows(productVos);

            return productVoList;

        } catch (Exception e) {
            e.printStackTrace();
            return TableDataInfo.build();
        }
    }

    /**
     * 获取销售订单详情
     */
    @GetMapping("/getSaleOrderDetail")
    public R<MobileSaleOrderInfoVo> getSaleOrderDetail(@RequestParam(value = "id", required = true) String id) {

        // 获取登录用户
//        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {
//            BaseSaleOrderVo baseSaleOrderVo = baseSaleOrderService.queryById(id);
//
//            BaseProductVo baseProductVo = baseProductService.queryById(baseSaleOrderVo.getProductId());
//            String productPosterUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductPoster());
//            baseProductVo.setProductPosterUrl(productPosterUrl);
//            String productThumbnailUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductThumbnail());
//            baseProductVo.setProductThumbnailUrl(productThumbnailUrl);
//            baseSaleOrderVo.setProductThumbnailUrl(productThumbnailUrl);
//
//            BaseDeviceVo baseDeviceVo = baseDeviceService.queryById(baseProductVo.getDeviceId());
//            String devicePosterUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDevicePoster());
//            baseDeviceVo.setDevicePosterUrl(devicePosterUrl);
//            String deviceThumbnailUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDeviceThumbnail());
//            baseDeviceVo.setDeviceThumbnailUrl(deviceThumbnailUrl);
//            baseProductVo.setDeviceInfo(baseDeviceVo);
//
//            baseSaleOrderVo.setProductInfo(baseProductVo);

            MobileSaleOrderInfoVo vo = appSaleService.getSaleOrderInfo(id);
            return R.ok(vo);

        } catch (Exception e) {
            return R.fail();
        }
    }

    /**
     * 校验短信验证码
     */
    private boolean validateSmsCode(String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + phonenumber);
        return code.equals(smsCode);
    }

    /**
     * 校验套餐信息
     */
    private boolean validateProductInfo(String productId) {
        BaseProductVo baseProductVo = baseProductService.queryById(productId);
        if (ObjectUtil.isNotEmpty(baseProductVo)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 创建销售订单
     */
    @PostMapping("/createSaleOrder")
    public R<?> createSaleOrder(@RequestBody @Validated SaleOrderCreateBo bo) {

        // 获取登录用户
        AppLoginUser loginUser = AppLoginHelper.getAppLoginUser();

        try {

            // 验证短信验证码
            if (!validateSmsCode(bo.getPhone(), bo.getSmsCode())) {
                return R.fail("短信验证码不正确");
            }

            // 验证套餐
            if (!validateProductInfo(bo.getProductId())) {
                return R.fail("套餐信息错误");
            }

            BaseSaleOrder saleOrder = appSaleService.createSaleOrder(
                bo.getProductId(),
                bo.getLastName(),
                bo.getGender(),
                bo.getPhone(),
                bo.getSmsCode(),
                bo.getCarNo()
            );

            return R.ok(saleOrder);

        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("创建销售订单失败");
        }
    }

    /**
     * 发送假的短信
     *
     * @param phonenumber
     * @param smsCode
     * @return
     */
    @PostMapping("/sendFakeSmsCode")
    public R<?> sendFakeSmsCode(@RequestParam(value = "phone") String phone) {
        String smsCode = appSmsService.sendFakeSmsCode(phone);
        return R.ok("模拟发送短信成功", smsCode);
    }

}
